package com.wutong.authority_server.security;

import com.baomidou.mybatisplus.extension.api.R;
import com.wutong.authority_server.utils.TokenUtil;
import com.wutong.common_server.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TokenLogoutHandler implements LogoutHandler {

    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(RedisTemplate redisTemplate) {

        this.redisTemplate = redisTemplate;
    }
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1 从header里面获取token
        //2 token不为空，移除token，从redis删除token
        String token = request.getHeader("Authorization");
        if(token != null) {
            //移除
            TokenUtil.removeToken(token);
            //从token获取用户名
            String username = TokenUtil.getUsername(token);
            redisTemplate.delete(username);
        }
    }

}
